import shutil
from pathlib import Path

def merge_directories(source_path, target_path, conflict_resolution='overwrite'):
    """
    递归合并源目录到目标目录[1,4](@ref)

    参数:
        source_path: 源目录路径
        target_path: 目标目录路径
        conflict_resolution: 冲突解决策略 ('overwrite', 'rename', 'skip')
    """
    source = Path(source_path)
    target = Path(target_path)

    if not source.exists():
        raise FileNotFoundError(f"源路径不存在: {source_path}")

    if not source.is_dir():
        raise ValueError(f"源路径不是目录: {source_path}")

    # 确保目标目录存在[4](@ref)
    target.mkdir(parents=True, exist_ok=True)

    # 遍历源目录中的所有项目[3](@ref)
    for item in source.iterdir():
        target_item = target / item.name

        if item.is_dir():
            # 递归处理子目录[1](@ref)
            merge_directories(item, target_item, conflict_resolution)
        else:
            # 处理文件
            handle_file_copy(item, target_item, conflict_resolution)


def handle_file_copy(source_file, target_file, conflict_resolution):
    """
    处理文件复制，包括冲突解决[4](@ref)
    """
    if not target_file.exists():
        # 目标文件不存在，直接复制
        shutil.copy2(source_file, target_file)
        print(f"复制: {source_file} -> {target_file}")
    else:
        # 处理文件冲突
        if conflict_resolution == 'overwrite':
            shutil.copy2(source_file, target_file)
            print(f"覆盖: {source_file} -> {target_file}")
        elif conflict_resolution == 'rename':
            # 生成新的文件名[1](@ref)
            new_target = generate_unique_filename(target_file)
            shutil.copy2(source_file, new_target)
            print(f"重命名复制: {source_file} -> {new_target}")
        elif conflict_resolution == 'skip':
            print(f"跳过: {source_file} (目标已存在)")
        else:
            raise ValueError(f"不支持的冲突解决策略: {conflict_resolution}")


def generate_unique_filename(file_path):
    """
    为冲突的文件生成唯一的文件名[1](@ref)
    """
    path = Path(file_path)
    stem = path.stem
    suffix = path.suffix
    parent = path.parent

    counter = 1
    while True:
        new_name = f"{stem}_{counter}{suffix}"
        new_path = parent / new_name
        if not new_path.exists():
            return new_path
        counter += 1